package com.orhon.smartcampus.modules.material.fetcher;

import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.base.gqlModel.GQLSchool;
import com.orhon.smartcampus.modules.base.mm.SchoolMapper;
import com.orhon.smartcampus.modules.material.dao.SiteDao;
import com.orhon.smartcampus.modules.material.entity.Campus;
import com.orhon.smartcampus.modules.material.entity.Site;
import com.orhon.smartcampus.modules.material.gqlModel.GQLCampus;
import com.orhon.smartcampus.modules.material.gqlModel.GQLSite;
import com.orhon.smartcampus.modules.material.mm.CampusMapper;
import com.orhon.smartcampus.modules.material.mm.SiteMapper;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class SiteFetcher  implements DataFetcher {
	@Autowired
	private SiteDao siteDao;

	@Autowired
	TokenService tokenService;
	
	@Override
	public Object get(DataFetchingEnvironment env) throws Exception {
		String token = tokenService.getSystemToken();
		if(token==null) {
			return  R.NoLogin();
		}
		Long schoolId = JwtUtils.getSchoolId(token);

		int id = Integer.parseInt(env.getArgument("id").toString());

		String hql = "from Site where deleted_at = null and id = "+id+" and school_id = " + schoolId;
		Site item =  siteDao.findId(hql, null);
		if(item!=null) {
			GQLCampus gqlCampus = null;
			if (env.getSelectionSet().contains("campus")){
				Campus campus = item.getMaterialCampusByCampusId();
				gqlCampus = CampusMapper.MAPPER.toCampus(campus);
			}
			
			GQLSchool GgqlSchool = null;
 			if (env.getSelectionSet().contains("school")){
 				Schools schools = item.getBaseSchoolsBySchoolId();
 				GgqlSchool = SchoolMapper.MAPPER.toSchool(schools);
 			}

			GQLSite site = SiteMapper.MAPPER.toSite(item);
			site.setCampus(gqlCampus);
			site.setSchool(GgqlSchool);
			return site;
		}
		return null;
	}
}
